package com.reservation.controller;

import com.reservation.entity.Reservation;
import com.reservation.entity.User;
import com.reservation.entity.Venue;
import com.reservation.service.ReservationService;
import com.reservation.service.VenueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/reservation")
public class ReservationController {
    
    @Autowired
    private ReservationService reservationService;
    
    @Autowired
    private VenueService venueService;
    
    /**
     * 预约列表页面
     */
    @GetMapping("/list")
    public String list(Model model, HttpSession session, 
                      @RequestParam(required = false) String keyword,
                      @RequestParam(required = false) String status) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        
        List<Reservation> reservations;
        if (user.getRole().equals("admin")) {
            // 管理员可以看到所有预约
            if (keyword != null && !keyword.isEmpty() || status != null && !status.isEmpty()) {
                reservations = reservationService.search(keyword, status);
            } else {
                reservations = reservationService.findAll();
            }
        } else {
            // 普通用户只能看到自己的预约
            reservations = reservationService.findByUserId(user.getId());
        }
        
        model.addAttribute("reservations", reservations);
        model.addAttribute("keyword", keyword);
        model.addAttribute("status", status);
        return "reservation/list";
    }
    
    /**
     * 添加预约页面
     */
//    @GetMapping("/add")
//    public String add(Model model) {
//        List<Venue> venues = venueService.findAll();
//        model.addAttribute("venues", venues);
//        return "reservation/add";
//    }

    @GetMapping("/add/{id}")
    public String add(@PathVariable Integer id, Model model) {
        Venue venue = venueService.findById(id);
        model.addAttribute("venue", venue);
        return "reservation/add";
    }
    
    /**
     * 添加预约
     */
    @PostMapping("/add")
    public String add(@ModelAttribute Reservation reservation, HttpSession session, RedirectAttributes redirectAttributes) throws ParseException {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }

        reservation.setUserId(user.getId());

        if (reservation.getStartTime() == null || reservation.getEndTime() == null) {
            redirectAttributes.addFlashAttribute("error", "开始时间和结束时间不能为空");
            return "redirect:/reservation/list";
        }

        // 确保前端传递的日期时间格式正确
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        Date startDate = null;
        Date endDate = null;

        try {
            // 将字符串转换为 Date 对象（可以用于比较）
            startDate = sdf.parse(reservation.getStartTime());
            endDate = sdf.parse(reservation.getEndTime());
        } catch (ParseException e) {
            redirectAttributes.addFlashAttribute("error", "日期格式无效，请使用正确的格式：yyyy-MM-dd'T'HH:mm");
            return "redirect:/reservation/add";
        }

        // 将 Date 转换为你需要的格式，并保存到实体类中
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedStartTime = outputFormat.format(startDate);
        String formattedEndTime = outputFormat.format(endDate);

        // 如果需要，你可以将日期字符串存储为其他格式
        reservation.setStartTime(formattedStartTime);
        reservation.setEndTime(formattedEndTime);

        // 检查时间冲突
        if (reservationService.checkTimeConflict(reservation.getVenueId(), formattedStartTime, formattedEndTime)) {
            redirectAttributes.addFlashAttribute("error", "所选时间段已被预约，请选择其他时间");
            return "redirect:/reservation/add";
        }

        reservationService.save(reservation);
        redirectAttributes.addFlashAttribute("success", "预约申请已提交，请等待审核");
        return "redirect:/reservation/list";
    }



    /**
     * 编辑预约页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        
        Reservation reservation = reservationService.findById(id);
        if (reservation == null) {
            return "redirect:/reservation/list";
        }
        
        // 只有预约本人或管理员可以编辑
        if (!user.getRole().equals("admin") && !reservation.getUserId().equals(user.getId())) {
            return "redirect:/reservation/list";
        }
        
        // 已审核通过的预约不能编辑
        if (!reservation.getStatus().equals("pending")) {
            return "redirect:/reservation/list";
        }
        
        List<Venue> venues = venueService.findAll();
        model.addAttribute("venues", venues);
        model.addAttribute("reservation", reservation);
        return "reservation/edit";
    }
    
    /**
     * 编辑预约
     */
    @PostMapping("/edit")
    public String edit(@ModelAttribute Reservation reservation, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        
        Reservation existingReservation = reservationService.findById(reservation.getId());
        if (existingReservation == null) {
            return "redirect:/reservation/list";
        }
        
        // 只有预约本人或管理员可以编辑
        if (!user.getRole().equals("admin") && !existingReservation.getUserId().equals(user.getId())) {
            return "redirect:/reservation/list";
        }
        
        // 已审核通过的预约不能编辑
        if (!existingReservation.getStatus().equals("pending")) {
            return "redirect:/reservation/list";
        }
        
        // 检查时间冲突（排除当前预约）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        String startTime = sdf.format(reservation.getStartTime());
        String endTime = sdf.format(reservation.getEndTime());
        
        if (reservationService.checkTimeConflict(reservation.getVenueId(), startTime, endTime)) {
            redirectAttributes.addFlashAttribute("error", "所选时间段已被预约，请选择其他时间");
            return "redirect:/reservation/edit/" + reservation.getId();
        }
        
        reservationService.update(reservation);
        redirectAttributes.addFlashAttribute("success", "预约信息已更新");
        return "redirect:/reservation/list";
    }
    
    /**
     * 删除预约
     */
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        
        Reservation reservation = reservationService.findById(id);
        if (reservation == null) {
            return "redirect:/reservation/list";
        }
        
        // 只有预约本人或管理员可以删除
        if (!user.getRole().equals("admin") && !reservation.getUserId().equals(user.getId())) {
            return "redirect:/reservation/list";
        }
        
        // 已审核通过的预约不能删除
        if (!reservation.getStatus().equals("pending")) {
            redirectAttributes.addFlashAttribute("error", "已审核通过的预约不能删除");
            return "redirect:/reservation/list";
        }
        
        reservationService.deleteById(id);
        redirectAttributes.addFlashAttribute("success", "预约已删除");
        return "redirect:/reservation/list";
    }
    
    /**
     * 更新预约状态（仅管理员）
     */
    @GetMapping("/updateStatus/{id}")
    public String updateStatus(@PathVariable Integer id, @RequestParam String status, 
                             HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null || !user.getRole().equals("admin")) {
            return "redirect:/user/login";
        }
        
        Reservation reservation = reservationService.findById(id);
        if (reservation == null) {
            return "redirect:/reservation/list";
        }
        
        reservationService.updateStatus(id, status);
        redirectAttributes.addFlashAttribute("success", "预约状态已更新");
        return "redirect:/reservation/list";
    }
} 